package com.javabean;

import java.math.BigDecimal;
import java.util.LinkedHashMap;
import java.util.Map;

/**
 * 购物车对象
 */
public class Cart {
    //private Integer totalcount;
    //private BigDecimal totalprice;
    private Map<Integer, CartItem> items = new LinkedHashMap<>();


//    public Cart(Integer totalcount, BigDecimal totalprice, Map<Integer, CartItem> items) {
//        this.totalcount = totalcount;
//        this.totalprice = totalprice;
//        this.items = items;
//    }

    public Cart() {
    }

    @Override
    public String toString() {
        return "Cart{" +
                "totalcount=" + getTotalcount() +
                ", totalprice=" + getTotalprice() +
                ", items=" + items +
                '}';
    }

    public void addItem(CartItem cartItem) {
        CartItem item = items.get(cartItem.getId());
        if (item == null) {
            items.put(cartItem.getId(), cartItem);
        } else {
            item.setCount(item.getCount() + 1);
            item.setTotalprice(item.getPrice().multiply(new BigDecimal(item.getCount())));
        }

    }

    public void deleteItem(Integer id) {
        items.remove(id);
    }

    public void clear() {
        items.clear();
    }

    public void updateCount(Integer id, Integer count) {
        CartItem cartItem = items.get(id);
        if (cartItem != null) {
            cartItem.setCount(count);
            cartItem.setTotalprice(cartItem.getPrice().multiply(new BigDecimal(cartItem.getCount())));
        }

    }

    public Integer getTotalcount() {
        Integer totalcount = 0;
        for (Map.Entry<Integer, CartItem> entry : items.entrySet()) {
            totalcount += entry.getValue().getCount();
        }
        return totalcount;
    }


    public BigDecimal getTotalprice() {
        BigDecimal totalprice = new BigDecimal(0);
        for (Map.Entry<Integer, CartItem> entry : items.entrySet()) {
            totalprice = totalprice.add(entry.getValue().getTotalprice());
        }
        return totalprice;
    }


    public Map<Integer, CartItem> getItems() {
        return items;
    }

    public void setItems(Map<Integer, CartItem> items) {
        this.items = items;
    }
}



